from nicegui import background_tasks, events, ui
from orm import manager, UserGroup, User, QuestionGroup
from tools.UserPage import User_page


class Search:

    def __init__(self) -> None:
        self.option = {}
        with ui.dialog() as self.dialog, ui.card().tight().classes('w-[800px] h-[600px]'):
            with ui.row().classes('w-full items-center px-4'):
                ui.icon('search', size='2em')
                ui.input(placeholder='Search documentation', on_change=self.handle_input) \
                    .classes('flex-grow').props('borderless autofocus')
                names = ['问题', '用户', '用户组']
                ui.select(names, multiple=True, value=names[:2], on_change=self.handle_input) \
                    .classes('w-1/3').bind_value_to(self.option, "search_option")
                ui.button('ESC').props('padding="2px 8px" outline size=sm color=grey-5').classes('shadow')
            ui.separator()
            self.results = ui.element('q-list').classes('w-full').props('separator')
        ui.keyboard(self.handle_keypress)

    def create_button(self) -> ui.button:
        return ui.button(on_click=self.dialog.open, icon='search').props('flat color=white')

    def handle_keypress(self, e: events.KeyEventArguments) -> None:
        if not e.action.keydown:
            return
        if e.key == '/':
            self.dialog.open()
        if e.key == 'k' and (e.modifiers.ctrl or e.modifiers.meta):
            self.dialog.open()

    def handle_input(self, e: events.ValueChangeEventArguments) -> None:
        async def handle_input():
            with self.results:
                self.results.clear()
                results = []
                if "问题" in self.option["search_option"]:
                    for result in manager.search_quesgroup_by_ques(e.value):
                        results.append(result)
                if "用户" in self.option["search_option"]:
                    for result in manager.searchUser(e.value):
                        results.append(result)
                if "用户组" in self.option["search_option"]:
                    for result in manager.searchUserGroup(e.value):
                        results.append(result)
                for result in results:
                    if isinstance(result, UserGroup):
                        with ui.element('q-item').props(f'clickable') \
                                .on('click', lambda id1=result.id: self.open_user_group(id1), []):
                            with ui.element('q-item-section'):
                                ui.label("UserGroup  ").classes("w-[60px]")
                                ui.label(result.group_name)
                    elif isinstance(result, User):
                        with ui.element('q-item').props(f'clickable') \
                                .on('click', lambda id1=result.id: self.open_user(id1), []):
                            with ui.element('q-item-section'):
                                ui.label("User  ").classes("w-[60px]")
                                ui.label(result.username)
                    elif isinstance(result, QuestionGroup):
                        with ui.element('q-item').props(f'clickable') \
                                .on('click', lambda id1=result.id: self.open_ques(id1), []):
                            with ui.element('q-item-section'):
                                ui.label("QuestionGroup  ").classes("w-[60px]")
                                ui.label(result.group_name)
        background_tasks.create_lazy(handle_input(), name='handle_search_input')

    async def open_ques(self, ques_group_id) -> None:
        ui.open("/question_group/{}".format(ques_group_id))
        self.dialog.close()

    async def open_user(self, userid) -> None:
        userpage = User_page(userid)
        userpage.open_page()

    async def open_user_group(self, user_group_id) -> None:
        ui.open("/user_group/{}".format(user_group_id))
        self.dialog.close()
